<template>
  <div class="common-layout">
    <el-container>
      <el-aside width="220px" class="aside">
        <div class="logo">
          <span>西安卡茨科技有限责任公司</span>
        </div>
        <div class="menu-container">
          <router-link to="/main/dashboard" class="menu-item">
            <i class="el-icon-data-analysis"></i>
            <span>仪表盘</span>
          </router-link>
          <router-link to="/main/project" class="menu-item">
            <i class="el-icon-folder"></i>
            <span>项目管理</span>
            <i class="el-icon-arrow-right"></i>
          </router-link>
          <router-link to="/main/task" class="menu-item">
            <i class="el-icon-s-order"></i>
            <span>任务管理</span>
            <i class="el-icon-arrow-right"></i>
          </router-link>
          <router-link to="/main/user" class="menu-item">
            <i class="el-icon-s-order"></i>
            <span>成员管理</span>
            <i class="el-icon-arrow-right"></i>
          </router-link>
          <router-link to="/main/file" class="menu-item">
            <i class="el-icon-s-order"></i>
            <span>文件管理</span>
            <i class="el-icon-arrow-right"></i>
          </router-link>
        </div>
      </el-aside>
      <el-container>
        <el-header class="header">
          <div class="search-container">
            <div class="search-box" :class="{ 'is-focused': isSearchFocused }">
              <i class="el-icon-search"></i>
              <input
                  type="text"
                  placeholder="搜索文件、文档、图片..."
                  @focus="isSearchFocused = true"
                  @blur="isSearchFocused = false"
                  v-model="searchQuery"
                  @keyup.enter="handleSearch"
              >
              <div class="search-actions" v-show="searchQuery || isSearchFocused">
                <button class="clear-btn" @click="clearSearch" v-if="searchQuery">
                  <i class="el-icon-close"></i>
                </button>
                <div class="divider" v-if="searchQuery"></div>
                <button class="search-btn" @click="handleSearch">
                  <span>搜索</span>
                  <span class="shortcut">⏎</span>
                </button>
              </div>
            </div>
          </div>
          <div class="user-info">
            <button class="upload-btn" @click="showUploadDialog">
              <i class="el-icon-upload2"></i>
              <span>上传文件</span>
            </button>
            <div class="user-profile">
              <div class="user-name">{{ userInfo.username }}</div>
              <div class="avatar">
                <el-avatar :size="40" :src="userInfo.avatar">
                  <img src="https://via.placeholder.com/40" alt="默认头像"/>
                </el-avatar>
              </div>
            </div>
          </div>
        </el-header>
        <el-main class="main">
          <router-view></router-view>
        </el-main>
      </el-container>
    </el-container>

    <!-- 上传文件对话框 -->
    <el-dialog
        v-model="uploadDialogVisible"
        :show-close="false"
        :close-on-click-modal="false"
        :close-on-press-escape="true"
        width="650px"
        top="10vh"
        class="upload-dialog-wrapper"
    >
      <upload-file @close="uploadDialogVisible = false" />
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios';
import UploadFile from "@/components/UploadFile.vue";
import ResourceService from "@/api/ResourceService.js"; // 引入MessageBox组件
import { ref, onMounted } from 'vue'


export default {
  setup() {
    const userInfo = ref({
      username: '',
      avatar: 'https://via.placeholder.com/40' // 默认头像
    })

    // 获取当前用户信息
    const getCurrentUser = async () => {
      try {
        const token = localStorage.getItem('token') // 假设token存储在localStorage
        const response = await axios.get('http://localhost:8080/auth/current-user', {
          headers: {
            Authorization: `Bearer ${token}`
          }
        })
        userInfo.value = {
          username: response.data.username,
          // 如果后端返回头像字段可以这样使用：
          avatar: response.data.avatar || 'https://via.placeholder.com/40'
        }
      } catch (error) {
        console.error('获取用户信息失败:', error)
        // 处理未认证情况
        if (error.response?.status === 401) {
          // 跳转到登录页
          window.location.href = '/login'
        }
      }
    }

    // 组件挂载时获取用户信息
    onMounted(() => {
      getCurrentUser()
    })

    return {
      userInfo
    }
  },
  components: {
    UploadFile,
  },
  data() {
    return {
      isSearchFocused: false,
      searchQuery: '',
      uploadDialogVisible: false,
      file: null,
      taskName: '',
      uploadMessage: '',
    };
  },
  methods: {
    showUploadDialog() {
      this.uploadDialogVisible = true;
    },
    async handleSearch() {
      if (!this.searchQuery.trim()) return;

      try {
        const response = await axios.get('http://localhost:8080/api/resources/search', {
          params: {
            fileName: this.searchQuery // 修改这里，将参数名改为fileName
          }
        });

        console.log('Search Results:', response.data);

        if (response.data && response.data.length > 0) {
          const item = response.data[0];
          this.$msgbox({
            title: '任务详情',
            message: `
          <div>
            <p><strong>分类类型:</strong> ${item.categoryType}</p>
            <p><strong>文件路径:</strong> ${item.filePath}</p>
            <p><strong>大小:</strong> ${item.formattedSize}</p>
            <p><strong>时间:</strong> ${item.formattedTime}</p>
            <p><strong>资源名称:</strong> ${item.resourceName}</p>
            <p><strong>资源类型:</strong> ${item.resourceType}</p>
            <p><strong>任务名称:</strong> ${item.taskName}</p>
            <p><strong>上传时间:</strong> ${item.uploadTime}</p>
            <p><strong>版本:</strong> ${item.version}</p>
          </div>
        `,
            dangerouslyUseHTMLString: true,
            customClass: 'message-box-custom-width'
          });
        } else {
          this.$msgbox({
            title: '提示',
            message: '没有找到相关资源。',
            customClass: 'message-box-custom-width'
          });
        }
      } catch (error) {
        console.error("There was an error fetching the search results!", error);
        this.$msgbox({
          title: '错误',
          message: '获取搜索结果时发生错误，请稍后再试。',
          customClass: 'message-box-custom-width'
        });
      }
    },
    clearSearch() {
      this.searchQuery = '';
    },
    handleFileChange(event) {
      this.file = event.target.files[0];
    },
    async upload() {
      if (!this.file || !this.taskName) {
        alert('请上传文件并填写任务名称');
        return;
      }
      try {
        const response = await ResourceService.uploadFile(this.file, this.taskName);
        this.uploadMessage = response;
      } catch (error) {
        this.uploadMessage = error.response && error.response.data ? error.response.data : '上传失败';
        console.error("Error during file upload:", error);
      }
    },
  },
};
</script>
<style lang="scss" scoped>
.common-layout {
  height: 100vh;

  .el-container {
    height: 100%;
  }

  .aside {
    background-color: #fff;
    border-right: 1px solid #e6e6e6;
    display: flex;
    flex-direction: column;
    transition: all 0.3s ease;
    box-shadow: 2px 0 8px rgba(0, 0, 0, 0.02);

    .logo {
      height: 60px;
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 0 20px;
      border-bottom: 1px solid #e6e6e6;
      background: linear-gradient(to right, #f8f9fa, #fff);

      span {
        font-size: 14px;
        font-weight: 600;
        color: #333;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        text-align: center;
        letter-spacing: 0.5px;
      }
    }

    .menu-container {
      flex: 1;
      padding: 15px 0;

      .menu-item {
        display: flex;
        align-items: center;
        padding: 12px 20px;
        color: #606266;
        text-decoration: none;
        position: relative;
        margin: 4px 0;
        transition: all 0.3s ease;

        i {
          margin-right: 12px;
          font-size: 18px;
          transition: all 0.3s ease;

          &.el-icon-arrow-right {
            position: absolute;
            right: 15px;
            font-size: 12px;
            opacity: 0;
            transform: translateX(-5px);
          }
        }

        span {
          font-size: 14px;
          transition: color 0.3s ease;
        }

        &:hover {
          background: linear-gradient(to right, #f0f5ff, transparent);
          color: #409EFF;
          padding-left: 24px;

          i {
            color: #409EFF;

            &.el-icon-arrow-right {
              opacity: 1;
              transform: translateX(0);
            }
          }
        }

        &.router-link-active {
          background: linear-gradient(to right, #ecf5ff, transparent);
          color: #409EFF;
          font-weight: 500;

          &::before {
            content: '';
            position: absolute;
            left: 0;
            top: 0;
            bottom: 0;
            width: 3px;
            background: linear-gradient(to bottom, #6c8cff, #409EFF);
            border-radius: 0 2px 2px 0;
          }

          i {
            color: #409EFF;

            &.el-icon-arrow-right {
              opacity: 1;
              transform: translateX(0);
            }
          }
        }
      }
    }
  }

  .header {
    background-color: #fff;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 20px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);

    .search-container {
      position: relative;
      width: 400px;
    }

    .search-box {
      display: flex;
      align-items: center;
      background-color: #f5f5f5;
      border-radius: 10px;
      padding: 5px 15px;
      transition: all 0.3s ease;
      border: 2px solid transparent;

      &.is-focused {
        background-color: #fff;
        border-color: #6c8cff;
        box-shadow: 0 0 0 4px rgba(108, 140, 255, 0.1);
      }

      i {
        color: #999;
        margin-right: 10px;
        font-size: 18px;
      }

      input {
        border: none;
        background: transparent;
        outline: none;
        width: 100%;
        height: 36px;
        font-size: 14px;
        color: #333;

        &::placeholder {
          color: #999;
        }
      }

      .search-actions {
        display: flex;
        align-items: center;
        gap: 8px;
      }

      .clear-btn {
        background: none;
        border: none;
        padding: 4px;
        cursor: pointer;
        color: #999;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;

        &:hover {
          background-color: #eee;
          color: #666;
        }
      }

      .divider {
        width: 1px;
        height: 20px;
        background-color: #ddd;
      }

      .search-btn {
        background: linear-gradient(135deg, #6c8cff, #5a78e6);
        color: white;
        border: none;
        border-radius: 6px;
        padding: 6px 12px;
        cursor: pointer;
        font-size: 14px;
        display: flex;
        align-items: center;
        gap: 8px;
        transition: all 0.2s;

        &:hover {
          background: linear-gradient(135deg, #5a78e6, #4967d5);
        }

        .shortcut {
          font-size: 12px;
          opacity: 0.8;
          padding: 2px 4px;
          background-color: rgba(255, 255, 255, 0.2);
          border-radius: 4px;
        }
      }
    }

    .user-info {
      display: flex;
      align-items: center;

      .upload-btn {
        display: flex;
        align-items: center;
        background: linear-gradient(135deg, #6c8cff, #5a78e6);
        color: white;
        border: none;
        border-radius: 8px;
        padding: 8px 16px;
        margin-right: 20px;
        cursor: pointer;
        font-size: 14px;
        transition: all 0.2s;
        box-shadow: 0 3px 8px rgba(108, 140, 255, 0.3);

        i {
          margin-right: 6px;
          font-size: 16px;
        }

        &:hover {
          background: linear-gradient(135deg, #5a78e6, #4967d5);
          transform: translateY(-2px);
          box-shadow: 0 5px 12px rgba(108, 140, 255, 0.4);
        }

        &:active {
          transform: translateY(0);
          box-shadow: 0 2px 5px rgba(108, 140, 255, 0.3);
        }
      }

      .user-profile {
        display: flex;
        align-items: center;
        cursor: pointer;
        padding: 5px;
        border-radius: 20px;
        transition: background-color 0.2s;

        &:hover {
          background-color: #f5f7fa;
        }

        .user-name {
          margin-right: 10px;
          font-size: 14px;
          font-weight: 500;
          color: #333;
        }

        .avatar {
          width: 40px;
          height: 40px;
          border-radius: 50%;
          overflow: hidden;
          box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);

          img {
            width: 100%;
            height: 100%;
            object-fit: cover;
          }
        }
      }
    }
  }

  .main {
    background-color: #f9f9f9;
    padding: 20px;
    overflow: auto;
  }
}

.search-dropdown {
  position: absolute;
  top: calc(100% + 5px);
  left: 0;
  right: 0;
  background-color: white;
  border-radius: 10px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  padding: 10px 0;
  z-index: 1000;

  .search-history {
    .history-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 0 15px 10px;
      border-bottom: 1px solid #f5f5f5;

      span {
        font-size: 13px;
        color: #999;
      }

      button {
        background: none;
        border: none;
        color: #6c8cff;
        font-size: 13px;
        cursor: pointer;
        padding: 4px 8px;
        border-radius: 4px;

        &:hover {
          background-color: #f5f7ff;
        }
      }
    }

    .history-list {
      max-height: 200px;
      overflow-y: auto;

      .history-item {
        display: flex;
        align-items: center;
        padding: 8px 15px;
        cursor: pointer;

        &:hover {
          background-color: #f5f7ff;

          .el-icon-close {
            opacity: 1;
          }
        }

        i.el-icon-time {
          color: #999;
          margin-right: 10px;
          font-size: 14px;
        }

        span {
          flex: 1;
          font-size: 14px;
          color: #333;
        }

        i.el-icon-close {
          color: #999;
          opacity: 0;
          padding: 4px;
          border-radius: 50%;
          transition: all 0.2s;

          &:hover {
            background-color: #eee;
            color: #666;
          }
        }
      }
    }
  }
}

@media (max-width: 768px) {
  .aside {
    display: none;
  }

  .header {
    .search-container {
      width: 200px;
    }

    .user-info {
      .upload-btn span {
        display: none;
      }

      .user-profile .user-name {
        display: none;
      }
    }
  }
}

/* 上传对话框样式 */
.upload-dialog-wrapper {
  :deep(.el-dialog) {
    border-radius: 16px;
    overflow: hidden;
    box-shadow: 0 20px 40px rgba(0, 0, 0, 0.15);
    margin: 0 auto;

    .el-dialog__header {
      display: none;
    }

    .el-dialog__body {
      padding: 0;
    }
  }
}

/* 添加对话框打开和关闭的动画 */
.v-enter-active,
.v-leave-active {
  transition: all 0.3s ease;
}

.v-enter-from,
.v-leave-to {
  opacity: 0;
  transform: scale(0.95);
}

.v-enter-to,
.v-leave-from {
  opacity: 1;
  transform: scale(1);
}

/* 添加遮罩层动画 */
:deep(.el-overlay) {
  backdrop-filter: blur(3px);
  transition: backdrop-filter 0.3s ease;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .upload-dialog-wrapper {
    :deep(.el-dialog) {
      width: 95% !important;
      margin: 0 auto;
    }
  }
}
</style>